package com.kk.base.controller.admin;

import com.kk.base.bean.CodeMsg;
import com.kk.base.bean.PageBean;
import com.kk.base.bean.Result;
import com.kk.base.entity.admin.AgingQuery;
import com.kk.base.service.admin.AgingQueryService;
import com.kk.base.util.ValidateEntityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/admin/agingQuery")
public class AgingQueryController {

    @Autowired
    private AgingQueryService agingQueryService;


    /**
     * 分页搜索按照来往地址模糊查询列表
     * @param model
     * @param agingQuery
     * @param pageBean
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(Model model, AgingQuery agingQuery, PageBean<AgingQuery> pageBean) {
        model.addAttribute("title", "报价时效列表");
        model.addAttribute("origin", agingQuery.getOrigin());
        model.addAttribute("pageBean", agingQueryService.findAllByToAndFromSite(pageBean, agingQuery));
        return "admin/aging_query/list";
    }

    /**
     * 进入添加页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(Model model) {
        return "admin/aging_query/add";
    }

    /**
     * 表单提交验证进行保存
     * @param agingQuery
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Result<Boolean> add(AgingQuery agingQuery) {
        //校验实体是否合法
        CodeMsg validate = ValidateEntityUtil.validate(agingQuery);
        if (validate.getCode() != CodeMsg.SUCCESS.getCode()) {
            return Result.error(validate);
        }

        //判断是否存在该地点
        if (agingQueryService.isExistOriginAndDestination(agingQuery.getOrigin(),agingQuery.getDestination())) {
            return Result.error(CodeMsg.ADMIN_AGINGQUERY_ISEXIST);
        }

        //到这说明一切符合条件，进行数据库新增
        if (agingQueryService.save(agingQuery) == null) {
            return Result.error(CodeMsg.ADMIN_AGINGQUERY_ADD_ERROR);
        }

        return Result.success(true);
    }

    /**
     * 删除一条记录
     * @param id
     * @return
     */
    @RequestMapping(value="/delete",method=RequestMethod.POST)
    @ResponseBody
    public Result<Boolean> delete(@RequestParam(name="id",required=true)Long id){
        try {
            agingQueryService.delById(id);
        } catch (Exception e) {
            return Result.error(CodeMsg.ADMIN_AGINGQUERY_DELETE_ERROR);
        }
        return Result.success(true);
    }

}
